package com.yanjiali.filter;

import com.alibaba.fastjson.JSONObject;
import com.yanjiali.properties.JwtProperties;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.Objects;

/**
 * @Package: com.yanjiali.filter
 * @Author: yanjiali
 * @Created: 2025/4/4 17:01
 * Jwt检查过滤器
 */
@Component
public class TokenCheckFilter implements GlobalFilter, Ordered {

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 获取对象顺序值，值越低优先级越高，即设置对应过滤器链路中的顺序
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }


    /**
     * 过滤处理逻辑
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 不需要 jwt 就能访问
        if (allowNoTokenAccess(exchange)) {
            return chain.filter(exchange);  //直接到下一个过滤器
        }

        // 获取用户的 jwt
        String token = getToken(exchange);
        if (StringUtils.isEmpty(token)) {
            return buildUNAuthorizedResult(exchange);
        }

        Boolean hasKey = stringRedisTemplate.hasKey(token);
        if(hasKey != null && hasKey) {
            return chain.filter(exchange);  //token有效
        }
        return buildUNAuthorizedResult(exchange);
    }

    /**
     * 检查对应请求路径是否需要携带jwt
     * @param exchange
     * @return true不需要，false 需要
     */
    private boolean allowNoTokenAccess(ServerWebExchange exchange) {
        String path = exchange.getRequest().getURI().getPath();
        if (jwtProperties.getNoTokenAccessUrls().contains(path)) {  //当前请求路径不需要携带jwt
            return true;
        }
        return false;
    }


    /**
     * 从Http请求头中获取对应的jwt串
     * @param exchange
     * @return
     */
    private String getToken(ServerWebExchange exchange) {
        ServerHttpRequest request = exchange.getRequest();
        HttpHeaders headers = request.getHeaders();
        String authorization = headers.getFirst(HttpHeaders.AUTHORIZATION);
        if (Objects.isNull(authorization) || authorization.trim().isEmpty()) {
            return null;
        }
        return authorization.replace("bearer ", "");
    }

    /**
     * 处理 jwt 串未通过验证的逻辑
     * @param exchange
     * @return
     */
    private Mono<Void> buildUNAuthorizedResult(ServerWebExchange exchange) {
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        response.getHeaders().set("Content-Type", "application/json;charset=UTF-8");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("error", "unauthorized");
        jsonObject.put("error_description", "invalid_token");
        DataBuffer dataBuffer =
                response.bufferFactory().wrap(jsonObject.toJSONString().getBytes());
        return response.writeWith(Flux.just(dataBuffer));
    }
}